<template>
	<view class="chatList" @touchstart="fadeShow = false" @tap="fadeShow = false">
		<u-sticky customNavHeight="0" class="sticky" :class="{ titleBg: scrollTop > 100 }">
			<topTitle title="聊天" :isBack="false">
				<template #right>
					<view @touchstart.stop class="addFriend">
						<image @tap.stop="fadeShow = !fadeShow" src="@/static/image/2.png" mode="widthFix" />
						<up-transition mode="fade" :show="fadeShow">
							<view class="triangle-up">
								<view @tap="goTo('/pages/group/initiateGroupChat?type=1')">发起群聊</view>
								<view @tap="goTo('/pages/create/addFriend')">添加好友</view>
								<!--#ifdef APP-PLUS-->
								<view @tap="scanCodeFn">扫一扫</view>
								<!--#endif-->
							</view>
						</up-transition>
					</view>
				</template>
			</topTitle>
		</u-sticky>

		<view class="com">


			<search @update:searchValue="searchFn" />

			<view class="msgList" v-if="chatList?.length">
				<view v-if="false">
					<view>
						<view>
							<image src="@/static/image/4.png" mode="widthFix" />
						</view>
						<view class="name">
							<view>消息通知</view>
							<view>今天...</view>
						</view>
					</view>
					<view>
						<view>12:09</view>
						<view>
							<image src="@/static/image/5.png" mode="widthFix" />
							<u-badge class="dot" type="success" max="99" :value="0"></u-badge>
						</view>
					</view>
				</view>
				<r-swipe-cell v-for="(item, idx) in filteredChatList" :key="idx" :autoClosed="true">
					<template #right>
						<view class="btns">
							<view @tap="actionItemFn(0, item)">{{ item.topSticky == 1 ? "解顶" : "置顶" }}</view>
							<view @tap="actionItemFn(1, item)">删除</view>
						</view>
					</template>
					<view class="msgItem" :class="{ 'touch-active': item.active }" @touchstart="item.active = true"
						@touchend="item.active = false" @tap="goDetail(item)">
						<view>
							<view>
								<up-avatar v-if="item.Type == 1" mode="aspectFill" :src="item.picture"
									size="50"></up-avatar>
								<nl-group-chat-avatar v-if="item.Type == 2" :imgs="item.member" round="22"
									img-round="100"></nl-group-chat-avatar>
							</view>
							<view class="name">
								<view>{{
                  item.Type == 2
                    ? item.group_name
                    : item.notes || item.nick_name
                }}</view>
								<view>
									<!-- :class="{ unread: item.Cmd == 4 || item.Cmd == 6 }" -->
									<view v-html="typeCopywriting(item)"> </view>
								</view>
							</view>
						</view>
						<view>
							<view>
								{{ formattingTime(item.Time, 2) }}
							</view>
							<view>
								<up-icon class="rotate" v-show="item.topSticky" name="download"></up-icon>
								<up-icon class="notDisturb" v-show="item.notDisturb" name="volume-off"></up-icon>
								<u-badge class="dot" type="success" max="99" :value="item.unread"></u-badge>
							</view>
						</view>
					</view>

				</r-swipe-cell>

			</view>
		</view>

		<up-back-top :scroll-top="scrollTop" duration="50" top="300"></up-back-top>
	</view>
</template>

<script setup lang="ts">
	import { ref, computed, watch, getCurrentInstance, reactive } from "vue";
	import { onPageScroll, onShow, onLoad } from "@dcloudio/uni-app";
	import { FriendApply, Friend, FriendInfoSelect } from "@/api/ImApi";
	import { useStore } from "@/stores";
	const instance = getCurrentInstance()?.appContext.config.globalProperties;
	const store = useStore();
	const latestData = computed(() => store.latestData);
	// 使用 reactive 创建响应式对象数组  
	const options2 = reactive([
		{
			text: '收藏',
			style: {
				backgroundColor: '#3c9cff'
			}
		},
		{
			text: '删除',
			style: {
				backgroundColor: '#f56c6c'
			}
		}
	]);
	watch(latestData, (newValue : any) => {
		console.log("首页消息监听", newValue);
		// 通知消息
		if (newValue.Grade == 2) {
			// 单聊
			if (newValue.Type == 1) {
				FriendApplyFn();
				FriendFn();
			}
			if (newValue.Type == 2) {
				// 修改群信息
				if (newValue.Cmd == 3 && newValue.Content.Group) {
					const index = chatList.value.findIndex(
						(e) => e.chatId === newValue.chatId
					);
					let obj = chatList.value[index];
					chatList.value[index] = {
						...obj,
						...newValue,
						...newValue.Content.Group,
					};
				}
				if (newValue.Cmd == 1) {
					getChatList();
				}
			}
		}
		if (newValue.Grade == 1) {
			// 单聊
			if (newValue.Type == 1) {
				const index = chatList.value.findIndex(
					(e) => e.SessionId === newValue.SessionId
				);

				if (newValue.Cmd != 7) {
					if (index !== -1) {
						let obj = chatList.value[index];
						chatList.value[index] = {
							...obj,
							...newValue,
							unread: obj.unread ? obj.unread + 1 : 1,
						};
					} else {
						getChatList();
					}
				}
			}

			// 群聊
			if (newValue.Type == 2) {
				const index = chatList.value.findIndex(
					(e) => e.chatId === newValue.chatId
				);

				if (index !== -1) {
					let obj = chatList.value[index];
					chatList.value[index] = {
						...obj,
						...newValue,
						unread: obj.unread ? obj.unread + 1 : 1,
					};
				} else {
					getChatList();
				}
			}
		}
	});

	// 进入聊天
	const goDetail = async (item : any) => {
		item.unread = 0;
		if (item.Type == 1) {
			instance?.goTo("/pages/chat/chat?user_id=" + item.user_id + "&Type=1");
		}
		if (item.Type == 2) {
			instance?.goTo("/pages/chat/chat?group_id=" + item.GroupId + "&Type=2");
		}
	};
	// 添加好友弹窗
	let fadeShow = ref<boolean>(false);
	// 好友申请列表
	let friendApplyList = ref<Array<any>>();
	const FriendApplyFn = async () => {
		if (uni.getStorageSync("FriendApply")) {
			friendApplyList.value = uni.getStorageSync("FriendApply");
		}
		friendApplyList.value = await FriendApply();
	};

	// 好友列表
	const FriendFn = async () => {
		await Friend();
	};

	// 聊天列表
	let chatList = ref<Array<any>>([]);
	const getChatList = async () => {
		chatList.value = await instance?.getUnreadCount();
		console.log("聊天列表", chatList.value);
	};

	const actionItemFn = async (index : number, item : any) => {

		// 置顶
		if (index == 0) {
			console.log(item);
			console.log(item.chatId, 111);
			item.topSticky = item.topSticky == 1 ? 0 : 1;
			await instance?.setChatList(item, item.chatId);
		}
		// 删除
		if (index == 1) {
			await instance?.deletingData(item);
			getChatList();
		}
	};

	// 滚动
	let scrollTop = ref<number>(0);
	onPageScroll((e) => {
		scrollTop.value = e.scrollTop;
	});

	// 过滤名称
	let searchValue = ref<string>("");
	const searchFn = (e : any) => {
		searchValue.value = e;
	};
	// 排序后的聊天列表
	const sortedChatList = computed(() => {
		return [...chatList.value].sort((a, b) => {
			// 将 null 或 undefined 的 topSticky 视为 0
			const topStickyA = a.topSticky ?? 0;
			const topStickyB = b.topSticky ?? 0;

			// 按 topSticky 降序排序 (1 在前)
			if (topStickyB !== topStickyA) {
				return topStickyB - topStickyA;
			}

			// 如果 topSticky 相同，再按时间降序排序
			return b.Time - a.Time;
		});
	});

	// 过滤后的聊天列表
	const filteredChatList = computed(() => {
		if (searchValue.value) {
			return sortedChatList.value.filter((item) => {
				const searchTarget =
					item.Type === 2 ? item.group_name : item.notes || item.nick_name;
				return searchTarget
					.toLowerCase()
					.includes(searchValue.value.toLowerCase());
			});
		} else {
			return sortedChatList.value;
		}
	});


	const scanCodeFn = () => {
		uni.scanCode({
			success: function (res) {
				console.log('条码类型：' + res.scanType);
				console.log('条码内容：' + res.result);
				searchAddFn(res.result)
			}
		});

	}
	// 前往添加好友
	const searchAddFn = (id_no:any) => {

		FriendInfoSelect({ id_no, loading: 1 })
			.then(async (e : any) => {
				let friendInfo = { ...e, id_no, type: 0 };
				let friendList = await instance?.$db.loadData("friendList", {
					user_id: e.user_id,
				});

				if (friendList.length) {
					instance?.goTo("/pages/chat/friendDetails?chatId=" + e.user_id);
				} else {
					instance?.goTo(
						"/pages/create/searchAdd?searchValue=" +
						encodeURIComponent(JSON.stringify(friendInfo))
					);
				}
			})

	};

	let myUserInfo = ref();

	onLoad(() => {
		myUserInfo.value = uni.getStorageSync("userInfo");
		if (!myUserInfo.value) {
			instance?.goTo("/pages/notLoggedIn/login");
			return;
		}

	});
	onShow(() => {
		myUserInfo.value = uni.getStorageSync("userInfo");
		if (!myUserInfo.value) {
			return;
		}
		getChatList();
		FriendApplyFn();
		FriendFn();
	});
</script>
<style scoped lang="scss">
	@import "../../static/scss/index.scss";
</style>